<?php
/**
 * Project: HTPHouDuan
 * User: xilibo
 * Date: 2018/1/24
 */

namespace app\common\model;

use think\Model;
use think\Db;

/**
 * 基础模型
 */
abstract class BaseModel extends Model
{
    protected $tableName = '';

    public function initialize()
    {
        $this->tableName = $this->tableName ? $this->tableName : $this->table;
    }

    public function getList($where = [])
    {
        $field = isset($where['field']) ? $where['field'] : [];
        $where = isset($where['where']) ? $where['where'] : [];
        $cacheKey = isset($where['cache_key']) ? $where['cache_key'] : false;
        $order = isset($where['order']) ? $where['order'] : 'id';
        $orderType = (isset($where['order_type']) && in_array(strtoupper($where['order_type']), ['ASC', 'DESC'])) ? $where['order_type'] : 'DESC';
        $orderBy = $order . ' ' . $orderType;
        $page = isset($where['page']) ? intval($where['page']) : 1;
        $pageSize = isset($where['page_size']) ? intval($where['page_size']) : 20;

    	$db = Db::name($this->tableName)->field($field)->where($where)
                    ->order($orderBy);
        if ($cacheKey){
            $db = $db->cache($cacheKey);
        }

        if (isset($where['page'])){
            return $db->page($page, $pageSize)->select();
        }

        return $db->paginate($pageSize);
    }

    public function getRow($where, $field = [], $cacheKey = false)
    {
        $row = Db::name($this->tableName)->field($field)->cache($cacheKey)->where($where)->find();

        return $row;
    }

    public function getValue($where,$value, $cacheKey = false)
    {
        $row = Db::name($this->table)->cache($cacheKey)->where($where)->value($value);

        return $row;
    }

    public function deleteIt($where)
    {
        return Db::name($this->tableName)->where($where)->delete();
    }

    public function saveData($data, $where = [], $cacheKey = false)
    {
        Db::startTrans();
        try{
            if (empty($where)){
                Db::name($this->tableName)->insert($data);
            }else {
                Db::name($this->tableName)->update($data, $where);
            }
            Db::commit();
        } catch(\Exception $e){
            Db::rollback();
            throw $e;
        }

        if ($cacheKey){
            cache($cacheKey, $data);
        }

        return true;
    }

    public function existsRow($where, $cacheKey = false)
    {
        $result = count(Db::name($this->tableName)->cache($cacheKey)->where($where)->find()) > 0;

        return $result;
    }
}
